package com.devmindset.legoframework.usage.client.component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.devmindset.legoframework.client.mvc.LegoComponent;
import com.devmindset.legoframework.client.mvc.LegoModel;
import com.devmindset.legoframework.client.mvc.metadata.ComponentStory;
import com.devmindset.legoframework.client.mvc.metadata.Stories;
import com.devmindset.legoframework.usage.client.datasource.OrderItemLocalDS;
import com.devmindset.legoframework.usage.client.event.Events;
import com.devmindset.legoframework.usage.client.records.OrderItemRecord;
import com.google.gwt.i18n.client.NumberFormat;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.RecordSummaryFunctionType;
import com.smartgwt.client.types.SummaryFunctionType;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.ListGridSummaryField;
import com.smartgwt.client.widgets.grid.SummaryFunction;

public class PendingOrdersComponent extends LegoComponent {
	
	private DataSource dataSource;
	
	/** {@inheritDoc} */
	@Override
	public Canvas construct(LegoModel model) {
		dataSource = OrderItemLocalDS.getInstance();

		ListGridField orderIdField = new ListGridField("orderID");
		orderIdField.setIncludeInRecordSummary(false);
		orderIdField.setSummaryFunction(SummaryFunctionType.COUNT);

		ListGridField itemDescriptionField = new ListGridField("itemDescription");

		ListGridField categoryField = new ListGridField("category");
		categoryField.setShowGridSummary(true);
		categoryField.setSummaryFunction(new SummaryFunction() {
			public Object getSummaryValue(Record[] records, ListGridField field) {
				Set<String> uniqueCategories = new HashSet<String>();

				for (int i = 0; i < records.length; i++) {
					Record record = records[i];
					uniqueCategories.add(((OrderItemRecord) record).getCategory());
				}
				return uniqueCategories.size() + " Categories";
			}
		});

		ListGridField shipDateField = new ListGridField("shipDate");
		shipDateField.setShowGroupSummary(true);
		shipDateField.setShowGridSummary(false);
		shipDateField.setSummaryFunction(SummaryFunctionType.MAX);

		ListGridField quantityField = new ListGridField("quantity");
		quantityField.setShowGroupSummary(false);
		quantityField.setShowGridSummary(false);

		ListGridField unitPriceField = new ListGridField("unitPrice");
		unitPriceField.setAlign(Alignment.RIGHT);
		unitPriceField.setCellFormatter(new CellFormatter() {
			public String format(Object value, ListGridRecord record, int rowNum,
					int colNum) {
				if (value == null)
					return null;
				try {
					NumberFormat nf = NumberFormat.getFormat(",0.00");
					return "$" + nf.format(((Number) value).doubleValue());
				} catch (Exception e) {
					return value.toString();
				}
			}
		});
		unitPriceField.setShowGroupSummary(false);
		unitPriceField.setShowGridSummary(false);

		ListGridSummaryField totalField = new ListGridSummaryField("total", "Total");
		totalField.setAlign(Alignment.RIGHT);
		totalField.setRecordSummaryFunction(RecordSummaryFunctionType.MULTIPLIER);
		totalField.setSummaryFunction(SummaryFunctionType.SUM);
		totalField.setShowGridSummary(true);
		totalField.setShowGroupSummary(true);
		totalField.setCellFormatter(new CellFormatter() {
			public String format(Object value, ListGridRecord record, int rowNum,
					int colNum) {
				if (value == null)
					return null;
				try {
					NumberFormat nf = NumberFormat.getFormat(",0.00");
					return "$" + nf.format(((Number) value).doubleValue());
				} catch (Exception e) {
					return value.toString();
				}
			}
		});

		final ListGrid listGrid = new ListGrid();

		listGrid.setWidth100();
		listGrid.setHeight100();
		listGrid.setAutoFetchData(true);

		listGrid.setShowAllRecords(true);
		listGrid.setDataSource(dataSource);
		listGrid.setCanEdit(true);
		listGrid.setGroupStartOpen("all");
		listGrid.setGroupByField("category");
		listGrid.setShowGridSummary(true);
		listGrid.setShowGroupSummary(true);
		listGrid.setAlternateRecordStyles(true);

		listGrid.setFields(orderIdField, itemDescriptionField, categoryField,
				shipDateField, quantityField, unitPriceField, totalField);
		
		return listGrid;
	}

	/** {@inheritDoc} */
	@Override
	public void calculate(LegoModel model) {
		//here's the place to recalculate your data source with updated info.
		List<OrderItemRecord> data = model.getModelData();
		dataSource.setTestData(data.toArray(new OrderItemRecord[] {}));
		dataSource.fetchData();
	}

	/** {@inheritDoc} */
	public ComponentStory myStory() {
		return Stories.component()
			.constructedBy(Events.RENDER_PENDING_ORDERS_COMPONENT)
			.knownAs("Pending Orders Component");
	}

}